// pages/mall/goods/goods.js
const util = require("../../../utils/util.js")

Page({

  data: {
    // 购物车收藏的商品数量
    shopCarCount: null,
    // 商品信息
    goods: null,
    // 商品属性
    goodsAttribute: {
      sex: null,
      age: null,
      color: null,
      count: 1,
      address: null
    }
  },

  // 查询商品信息，包含商品封面信息
  selectGoodsCascade: function(this_, param) {
    return util.requestByPost("/gdd/xcx/selectGoodsCascade", param, {
      isLogin: false,
      isPrePage: true
    }).then(res => {
      this_.setData({
        goods: res.length === 1 ? res[0] : null
      })
    })
  },

  // 查询购物车商品数量
  selectShopCarCount: function(this_) {
    return util.requestByPost("/gdd/xcx/selectShopCarCount", {}, {
      isLogin: true,
      isPrePage: true
    }).then(res => {
      this_.setData({
        shopCarCount: res
      });
    })
  },

  // 查询当前用户的默认收货地址
  selectWxUser: function() {
    if (!wx.getStorageSync("address")) {
      return util.requestByPost("/gdd/xcx/selectWxUser", {}, {
        isLogin: true,
        isPrePage: true
      }).then(res => {
        if (res.length > 0 && res[0].address) {
          wx.setStorageSync("address", res[0].address)
        }
      })
    }
  },

  /**
   * 加载数据
   */
  loadData: function() {
    // 重置数据
    this.setData({
      authDialogClosed: true,
      goods: null,
      shopCarCount: null,
      goodsAttribute: {
        sex: null,
        age: null,
        color: null,
        count: 1,
        address: null
      }
    })
    this.selectShopCarCount(this).then(this.selectWxUser()).then(this.selectGoodsCascade(this, {
      'isActive': '0',
      'id': this.data.goodsId
    }))
  },

  /**
   * 页面加载时触发。一个页面只会调用一次，可以在 onLoad 的参数中获取打开当前页面路径中的参数
   */
  onLoad: function(options) {
    // 商品编号
    this.data.goodsId = options.id;
    // 加载数据
    this.loadData()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.loadData()
  },

  /**
   * 选择sex
   */
  onSelectSex: function(event) {
    const sex = event.currentTarget.dataset.sex
    this.data.goodsAttribute.sex = sex
    this.setData({
      goodsAttribute: this.data.goodsAttribute
    });
  },

  /**
   * 选择age
   */
  onSelectAge: function(event) {
    const age = event.currentTarget.dataset.age
    this.data.goodsAttribute.age = age
    this.setData({
      goodsAttribute: this.data.goodsAttribute
    });
  },

  /**
   * 选择color
   */
  onSelectColor: function(event) {
    const color = event.currentTarget.dataset.color
    this.data.goodsAttribute.color = color
    this.setData({
      goodsAttribute: this.data.goodsAttribute
    });
  },

  /**
   * 购买数量-1
   */
  onJianCount: function(event) {
    this.data.goodsAttribute.count -= 1
    if (this.data.goodsAttribute.count == 0) {
      this.data.goodsAttribute.count = 1
    }
    this.setData({
      goodsAttribute: this.data.goodsAttribute
    });
  },

  /**
   * 购买数量+1
   */
  onJiaCount: function(event) {
    this.data.goodsAttribute.count += 1
    this.setData({
      goodsAttribute: this.data.goodsAttribute
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    return {
      title: this.data.goods.name,
      path: '/pages/mall/goods/goods?id=' + this.data.goods.id
    }
  },

  /**
   * 跳转到购物车主菜单
   */
  onShopCar: function(event) {
    wx.switchTab({
      url: "/pages/shopCar/shopCar",
    })
  },

  /**
   * 添加商品到购物车、立即预约
   */
  onOperation: function(event) {
    const this_ = this;
    const goods = {
      goodsTypeId: this.data.goods.goodsTypeId, // 商品分类编号
      goodsTypeName: this.data.goods.goodsType.name, // 商品分类名称
      goodsSrc: this.data.goods.cover.src, // 商品封面
      goodsId: this.data.goods.id, // 商品编号
      goodsName: this.data.goods.name, // 商品名称
      goodsPrice: this.data.goods.price, // 商品价格
      goodsCount: this.data.goodsAttribute.count, // 商品数量
      goodsRemark: null, // 商品备注信息（sex、age、color）
      goodsAddress: null, // 收货信息
    }
    /**
     * 判断该商品是否有附加属性
     */
    if (this.data.goods.goodsType.name == "犬类" || this.data.goods.goodsType.name == "猫类") {
      let goodsRemark = "";
      if (this.data.goodsAttribute.sex) {
        goodsRemark += "性别: " + this.data.goodsAttribute.sex + ";"
      } else {
        wx.showToast({
          title: "请选择性别",
          icon: "none",
          duration: 500,
          mask: true
        })
        return
      }
      if (this.data.goodsAttribute.age) {
        goodsRemark += "年龄: " + this.data.goodsAttribute.age + ";"
      } else {
        wx.showToast({
          title: "请选择年龄",
          icon: "none",
          duration: 500,
          mask: true
        })
        return
      }
      if (this.data.goodsAttribute.color) {
        goodsRemark += "颜色: " + this.data.goodsAttribute.color + ";"
      } else {
        wx.showToast({
          title: "请选择颜色",
          icon: "none",
          duration: 500,
          mask: true
        })
        return
      }
      goods.goodsRemark = goodsRemark;
    }
    /**
     * 判断该商品收货地址是否填写
     */
    const address = wx.getStorageSync("address")
    if (address) {
      goods.goodsAddress = address
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '请先到“个人中心”中设置默认收获地址',
        success: res => {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/user/user',
            })
          }
        }
      })
      return
    }
    const operationType = event.currentTarget.dataset.operationType
    if (operationType === 'shopCar') {
      /**
       * 添加到购物车
       */
      util.requestByPost("/gdd/xcx/modifyShopCar", goods, {
        isLogin: true,
        isPrePage: false
      }).then(res => {
        wx.showToast({
          title: "添加成功",
          icon: "success",
          mask: true,
          complete: () => {
            this_.setData({
              shopCarCount: this_.data.shopCarCount + 1
            })
          }
        })
      })
    } else {
      /**
       * 预约
       */
      const orderId = util.guid()
      const amount = goods.goodsPrice * goods.goodsCount
      const state = "0"
      goods.id = util.guid()
      goods.orderId = orderId
      util.requestByPost(`/gdd/xcx/modifyWxOrder`, {
        id: orderId,
        amount: amount,
        state: state,
        wxOrderGoods: [goods]
      }, {
        isLogin: true,
        isPrePage: false
      }).then(res => {
        wx.showToast({
          title: "预约成功",
          icon: "success",
          mask: true
        })
      })
    }
  }

})